package com.oscar.ehome.view.teamview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.fragment.BaseFragment;
import com.oscar.ehome.bean.UsersBean;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.teamBean.CusourTeamBean;
import com.oscar.ehome.bean.teamBean.TeamListBean;
import com.oscar.ehome.bean.teamBean.UserAppInfoBean;
import com.oscar.ehome.bean.teamBean.UserRoleStaticBean;
import com.oscar.ehome.bean.teamBean.UserStartStaticBean;
import com.oscar.ehome.presenter.TeamPresenter;
import com.oscar.ehome.provider.teamlist.WordsNavigation;
import com.oscar.ehome.utils.spinerpopwindow.AbstractSpinerAdapter;
import com.oscar.ehome.utils.spinerpopwindow.SpinerPopWindow;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.teamview.adapter.TeamAdapter;
import com.oscar.ehome.view.teamview.view.TeamListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by on 2017/5/19 16:11.
 * 团队页面
 *
 * @author mengwanhe
 */

public class TeamFragment extends BaseFragment<TeamListView,TeamPresenter> implements TeamListView, AbstractSpinerAdapter.IOnItemSelectListener,
        TeamAdapter.IntentListener, WordsNavigation.onWordsChangeListener, AbsListView.OnScrollListener, ProgressFrameLayout.AgainRequestListener {

    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * view
     */
    @BindView(R.id.rv)
    ListView rv;
    /**
     * 字母列表
     */
    @BindView(R.id.indexBar)
    WordsNavigation word;
    /**
     * 下拉列表图片
     */
    @BindView(R.id.img_spinner)
    ImageView imgSpinner;
    /**
     * 标题
     */
    @BindView(R.id.liear_title)
    LinearLayout liearTitle;
    /**
     * 统计图
     */
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    /**
     * 标题
     */
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;

    Unbinder unbinder;
    /**
     * 通讯录中间索引
     */
    @BindView(R.id.tv)
    TextView tv;

    @BindView(R.id.team_fragment)
    FrameLayout teamFragment;
    /**
     * 无网络布局
     */
    @BindView(R.id.teams_fragment)
    ProgressFrameLayout teamsFragment;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    private View view;
    //adapter
    private TeamAdapter mAdapter;
    //请求数据
    TeamPresenter teamPresenter;

    //我的团队
    private List<String> nameList = new ArrayList<String>();
    //团队列表
    List<TeamListBean.ListBean> mDatas = new ArrayList<>();
    //排序后的团队列表
    List<TeamListBean.ListBean> mDatas_list = new ArrayList<>();
    //排序的列表
    List<CusourTeamBean> list = new ArrayList<>();
    //筛选框
    SpinerPopWindow mSpinerPopWindow;
    String username = "";

    private Handler handler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_team, null);
        unbinder = ButterKnife.bind(this, view);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        initView();
        initData();
        onClicks();
        return view;
    }

    @Override
    protected TeamPresenter createPresenter() {
        teamPresenter = new TeamPresenter(this);
        return teamPresenter;
    }

    /**
     * 初始化view
     */
    private void initView() {
        titleTopbar.setText("全部下级");
        imgSpinner.setVisibility(View.VISIBLE);
        titleRightLayput.setVisibility(View.VISIBLE);
        titleImgRight.setVisibility(View.VISIBLE);
        titleImgRight.setImageResource(R.mipmap.zhiji);

        nameList.add("全部下级");
        nameList.add("直属下级");
        mSpinerPopWindow = new SpinerPopWindow(getActivity());
        mSpinerPopWindow.refreshData(nameList, 0);
    }

    /**
     * 绑定点击事件
     */
    private void onClick() {
        //设置列表点击滑动监听
        mAdapter.setOnINtentClickListener(this);
        handler = new Handler();
        word.setOnWordsChangeListener(this);
        rv.setOnScrollListener(this);
    }

    public void onClicks() {
        mSpinerPopWindow.setItemListener(this);
        teamsFragment.setAgainRequestListener(this);
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(getActivity())) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            teamsFragment.stopRefresh();
            teamFragment.setVisibility(View.VISIBLE);
            teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken(),
                    SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUuid(), "1");
            showLoading();
        } else {
            teamsFragment.setLoadFail();
            teamsFragment.setVisibility(View.VISIBLE);
            teamFragment.setVisibility(View.GONE);
        }
    }

    /**
     * 排序
     *
     * @param mDatas
     */
    public void setListBean(List<TeamListBean.ListBean> mDatas) {
        for (int i = 0; i < mDatas.size(); i++) {
            list.add(new CusourTeamBean(mDatas.get(i).getName()));
        }
        //对集合排序
        Collections.sort(list, new Comparator<CusourTeamBean>() {
            @Override
            public int compare(CusourTeamBean o1, CusourTeamBean o2) {
                return o1.getPinyin().compareTo(o2.getPinyin());
            }
        });

        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            for (int j = 0; j < mDatas.size(); j++) {
                String names = mDatas.get(j).getName();
                if (name.equals(mDatas.get(j).getName())) {
                    mDatas_list.add(mDatas.get(j));
                    break;
                }
            }
        }
    }

    @OnClick({R.id.liear_title, R.id.title_img_right})
    public void OnClicked(View view) {
        switch (view.getId()) {
            case R.id.liear_title://标题筛选
                mSpinerPopWindow.showAsDropDown(liearTitle, 0, 40);
                break;
            case R.id.title_img_right://统计图
                if (mDatas.size() > 0) {
                    String userBean = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUserMessage();
                    UsersBean userBe = new Gson().fromJson(userBean, UsersBean.class);
                    if (userBe != null) {
                        Intent intent = new Intent(getActivity(), TeamCountViewActivity.class);
                        intent.putExtra("member_name", userBe.getName());
                        intent.putExtra("id", SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUuid());
                        startActivity(intent);
                    }
                } else {
                    ToastUtil.show(getActivity(), "团队暂无人员");
                }
                break;
        }
    }

    /**
     * 团队列表数据
     *
     * @param TeamListBean
     */
    @Override
    public void LoadUserTeamAppList(TeamListBean TeamListBean) {
        dismissLoading();
        if (TeamListBean != null) {
            mDatas = new ArrayList<>();
            list = new ArrayList<>();
            mDatas_list = new ArrayList<>();
            mDatas = TeamListBean.getList();
            if (mDatas.size() > 0) {
                setListBean(mDatas);

                mAdapter = new TeamAdapter(getActivity(), mDatas_list, list);
                rv.setAdapter(mAdapter);
                onClick();
            } else {
                teamsFragment.setNoResult();
                teamFragment.setVisibility(View.GONE);
            }
        } else {
            teamsFragment.setNoResult();
            teamFragment.setVisibility(View.GONE);
        }
    }

    @Override
    public void getRoalList(TeamListBean TeamListBean) {

    }

    @Override
    public void getStartLeves(TeamListBean TeamListBean) {

    }

    @Override
    public void LoadUserRoleStatisticsAppList(UserRoleStaticBean userRoleStaticBean) {
    }

    @Override
    public void LoadUserStartStatisticsAppList(UserStartStaticBean userRoleStaticBean) {

    }

    @Override
    public void LoadUserAppInfo(UserAppInfoBean userAppInfoBean) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        if (getActivity() != null)
            ToastUtil.show(getActivity(), "请求失败，请重试！");
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getActivity().getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 筛选团队列表
     *
     * @param pos
     */
    @Override
    public void onItemClick(int pos) {
        setHero(pos);
    }

    /**
     * 筛选团队列表
     *
     * @param pos
     */
    private void setHero(int pos) {
        if (pos >= 0 && pos <= nameList.size()) {
            String value = nameList.get(pos);
            titleTopbar.setText(value);
            if (pos == 0) {
                teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken(),
                        SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUuid(), "1");
                showLoading();
            } else {
                teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken(),
                        SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUuid(), "2");
                showLoading();
            }
        }
    }

    @Override
    public void onIntentClick(int postion, int team_type) {
        if (team_type == 1) {//个人团队页
            if (!mDatas_list.get(postion).getChildNum().equals("0") && !mDatas_list.get(postion).getAllChildNum().equals("0")) {
                Intent intent_list = new Intent(getActivity(), TeamListActivity.class);
                intent_list.putExtra("id", mDatas_list.get(postion).getId());
                intent_list.putExtra("ids", "");//职级ID
                intent_list.putExtra("name", mDatas_list.get(postion).getName());
                intent_list.putExtra("chaungtuan", 2);
                intent_list.putExtra("chaun", 2);
                startActivity(intent_list);
            } else {
                ToastUtil.show(getActivity(), R.string.nodatamesage);
            }
        } else if (team_type == 2) {//个人信息页
            Intent intent = new Intent(getActivity(), TeamDetailActivity.class);
            intent.putExtra("id", mDatas_list.get(postion).getId());
            intent.putExtra("set", 2);
            startActivity(intent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //当滑动列表的时候，更新右侧字母列表的选中状态
        if (list.size() > 0) {
            word.setTouchIndex(list.get(firstVisibleItem).getHeaderWord());
        }
    }

    @Override
    public void wordsChange(String words) {
        updateWord(words);
        updateListView(words);
    }

    /**
     * @param words 首字母
     */
    private void updateListView(String words) {
        for (int i = 0; i < list.size(); i++) {
            String headerWord = list.get(i).getHeaderWord();
            //将手指按下的字母与列表中相同字母开头的项找出来
                if (words.equals(headerWord)) {
                //将列表选中哪一个
                rv.setSelection(i);
                //找到开头的一个即可
                return;
            }
        }
    }

    /**
     * 更新中央的字母提示
     *
     * @param words 首字母
     */
    private void updateWord(String words) {
        tv.setText(words);
        tv.setVisibility(View.VISIBLE);
        //清空之前的所有消息
        handler.removeCallbacksAndMessages(null);
        //1s后让tv隐藏
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv.setVisibility(View.GONE);
            }
        }, 500);
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(getActivity(), R.string.pull_to_refresh_network_error);
        }
    }
}
